package com.test.burnincash.util_burnin.http_burnin;

import android.content.pm.PackageManager;
import android.os.Build;

import androidx.annotation.NonNull;

import com.test.burnincash.bean_burnin.config_info_burnin.UrlInfo_burnin;
import com.test.burnincash.util_burnin.StringUtil_burnin;
import com.test.burnincash.util_burnin.ThreadUtil_burnin;
import com.test.burnincash.util_burnin.analytics_burnin.util_burnin.AnalyticsUtil_burnin;
import com.test.burnincash.util_burnin.helper_burnin.UserInfoHelper_burnin;
import com.test.burnincash.activity_fragment_burnin.base_burnin.BaseApplication_burnin;
import com.test.burnincash.constant_burnin.Constant_burnin;
import com.test.burnincash.constant_burnin.Url_burnin;
import com.test.burnincash.BuildConfig;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Locale;
import java.util.Objects;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

public class HttpManager_burnin {

    private String upload_Info_Url = "";

    private HttpManager_burnin() {
        if (BuildConfig.DEBUG) {
            mHttpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        }

//            @SuppressLint({"TrustAllX509TrustManager", "CustomX509TrustManager"}) final X509TrustManager trustManager = new X509TrustManager() {
//
//                @Override
//                public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) {
//
//                }
//
//                @Override
//                public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) {
//
//                }
//
//                @Override
//                public X509Certificate[] getAcceptedIssuers() {
//                    return new X509Certificate[0];
//                }
//            };
//            SSLContext sslContext = SSLContext.getInstance("TLS");
//            sslContext.init(null, new X509TrustManager[]{trustManager}, new SecureRandom());

        mClient = new OkHttpClient.Builder()
                .hostnameVerifier(new TrustAllCerts.TrustAllHostnameVerifier())
                .retryOnConnectionFailure(true)
                .addNetworkInterceptor(mHttpLoggingInterceptor)
                .addInterceptor(new ReqInterceptor_burnin())
                .callTimeout(5000, TimeUnit.MILLISECONDS)
                .build();
    }

    private static class Inner {
        private static final HttpManager_burnin instance = new HttpManager_burnin();
    }

    public static HttpManager_burnin getInstance() {
        return Inner.instance;
    }

    private static OkHttpClient mClient;

    private static final HttpLoggingInterceptor mHttpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLogger_burnin());

    public String getUpload_Info_Url() {
        return StringUtil_burnin.getSafeString(upload_Info_Url);
    }

    public void setUpload_Info_Url(String upload_Info_Url) {
        this.upload_Info_Url = upload_Info_Url;
    }

    //请求响应回调
    private final Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, @NonNull IOException e) {
            HttpPresenter_burnin.getInstance().showToastOnUiThread("Request Fail");
            ThreadUtil_burnin.getInstance().runOnUiThread(() -> HttpPresenter_burnin.getInstance().progressBarDialogDismiss());
            //Log.e("Http Response", "Request Fail  "+call.request().url());
        }

        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            String body = Objects.requireNonNull(response.body()).string();
            ThreadUtil_burnin.getInstance().runOnUiThread(() -> HttpPresenter_burnin.getInstance().progressBarDialogDismiss());
            try {
                String word = StringUtil_burnin.getUrlSuffix(response.request().url().toString());
                handleResponse(word, new JSONObject(body));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    //处理响应
    private void handleResponse(String lastWord, JSONObject responseJson) {
        ThreadUtil_burnin.getInstance().runOnUiThread(() -> HttpPresenter_burnin.getInstance().notifyActivityHandleResponse(lastWord, responseJson));
    }

    //获取初始化JSON对象
    @NonNull
    private JSONObject getRequestJson() {
        return getRequestJson(new JSONObject());
    }

    private JSONObject getRequestJson(JSONObject jsonObject) {
        try {
            jsonObject.put("isLimitAdTrackingEnabled", AnalyticsUtil_burnin.INSTANCE.getAdEnabled() + "");
            jsonObject.put("aduid", AnalyticsUtil_burnin.INSTANCE.getAdId());
            jsonObject.put("aduidPath", AnalyticsUtil_burnin.INSTANCE.getAndroidId());
            jsonObject.put("version", Constant_burnin.APP_VERSION.trim());
            jsonObject.put("token", UserInfoHelper_burnin.getInstance().getToken().trim());
            jsonObject.put("androidId", AnalyticsUtil_burnin.INSTANCE.getAndroidId());
            jsonObject.put("userId", UserInfoHelper_burnin.getInstance().getUserId().trim());
            jsonObject.put("advertId", AnalyticsUtil_burnin.INSTANCE.getAdId());
            jsonObject.put("product", Constant_burnin.PRODUCT.trim());
            jsonObject.put("clientType", Constant_burnin.CLIENT.trim());
            jsonObject.put("apiVersion", "v3");
            return jsonObject;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    //发送请求
    private void request(String lastWord, String jsonString) {
        requestWithoutCountryPrefix(Url_burnin.PATH_GLOBAL + lastWord,jsonString);
    }

    //发送请求（不带国家前缀）
    private void requestWithoutCountryPrefix(String lastWord, String jsonString) {

        ThreadUtil_burnin.getInstance().runOnUiThread(() -> HttpPresenter_burnin.getInstance().progressBarDialogShow());

        ThreadUtil_burnin.getInstance().runOnChildThread(() -> {
            MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
            Request request = new Request.Builder()
                    .url(Url_burnin.Url_Base + lastWord)
                    .post(RequestBody.Companion.create(jsonString, mediaType))
                    .build();
            Call call = mClient.newCall(request);
            call.enqueue(callback);
        });
    }

    /**
     * 获取Url
     */
    public void requestUrls(){
        request(Url_burnin.PATH_REQUEST_URLS,getRequestJson().toString());
    }

    //获取App配置
    public void getAppShowInfo() {
        request(Url_burnin.PATH_APP_SHOW_INFO, getRequestJson().toString());
    }

    //获取登录验证码
    public void requestOtpCode(String phoneNum) {
        UserInfoHelper_burnin.getInstance().setMobile(StringUtil_burnin.getSafeString(phoneNum));
        JSONObject jsonObject = getRequestJson();
        try {
            //jsonObject.put("channelCode", GPInstallHelper.getInstance().getInstallReferrer().trim());
            //jsonObject.put("subChannelCode", GPInstallHelper.getInstance().getInstallReferrer().trim());
            //jsonObject.put("code", "");
            jsonObject.put("mobile", phoneNum.trim());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request(Url_burnin.PATH_SMS_CODE, jsonObject.toString());
    }

    //注册登录-有验证码
    public void userLogin(String phoneNum, String verCode) {
        UserInfoHelper_burnin.getInstance().setMobile(StringUtil_burnin.getSafeString(phoneNum));
        JSONObject jsonObject = getRequestJson();
        try {
            jsonObject.put("channelCode", AnalyticsUtil_burnin.INSTANCE.getInstallReferrer());
            jsonObject.put("subChannelCode", AnalyticsUtil_burnin.INSTANCE.getInstallReferrer());
            jsonObject.put("code", verCode.trim());
            jsonObject.put("mobile", phoneNum.trim());
            jsonObject.put("notBindWalletFlag", "YES");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request(Url_burnin.PATH_USER_LOGIN, jsonObject.toString());
    }

    //注册登录-老用户
    public void userLoginOldUser(String phoneNum) {
        UserInfoHelper_burnin.getInstance().setMobile(StringUtil_burnin.getSafeString(phoneNum));
        JSONObject jsonObject = getRequestJson();
        try {
            jsonObject.put("channelCode", AnalyticsUtil_burnin.INSTANCE.getInstallReferrer());
            jsonObject.put("subChannelCode", AnalyticsUtil_burnin.INSTANCE.getInstallReferrer());
            jsonObject.put("code", "0000");
            jsonObject.put("mobile", phoneNum.trim());
            jsonObject.put("directLoginFlag","YES");
            jsonObject.put("notBindWalletFlag","YES");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request(Url_burnin.PATH_USER_LOGIN, jsonObject.toString());
    }

    //提交用户反馈
    public void submitServiceFeedback(String type, String opinion) {
        JSONObject jsonObject = getRequestJson();
        try {
            jsonObject.put("type", type);
            jsonObject.put("opinion", opinion);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request(UrlInfo_burnin.getInstance().getNft(), jsonObject.toString());
    }

    //获取银行列表（尼日）
    public void fetchBankCodes_Niri() {
        request(UrlInfo_burnin.getInstance().getF5r(), getRequestJson().toString());
    }

    //请求用户流程状态
    public void requestUserProcess() {
        request(UrlInfo_burnin.getInstance().getHrt(), getRequestJson().toString());
    }

    //上传用户信息
    public void uploadInfo(String url, TreeMap<String, String> dataMap) {
        try {
            JSONObject jsonObject = getRequestJson();
            for (String k : dataMap.keySet()) {
                String key = StringUtil_burnin.getSafeString(k);
                String value = StringUtil_burnin.getSafeString(dataMap.get(k));
                jsonObject.put(key, value);
            }
            HttpManager_burnin.getInstance().setUpload_Info_Url(url);;
            String prefix = Url_burnin.PATH_GLOBAL;
            if (!url.startsWith(prefix)) url = prefix + url;
            requestWithoutCountryPrefix(url, jsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //请求额度列表
    public void queryLoanLimit() {
        request(UrlInfo_burnin.getInstance().getGr3(), getRequestJson().toString());
    }

    //请求借款申请页信息/贷款详情
    public void requestLoanApplyDetail() {
        request(UrlInfo_burnin.getInstance().getJhk(), getRequestJson().toString());
    }

    //发起借款申请
    public void loanApply() {
        request(UrlInfo_burnin.getInstance().getRfi(), getRequestJson().toString());
    }

    //获取还款信息
    public void getRepayDetail() {
        request(UrlInfo_burnin.getInstance().getLhj(), getRequestJson().toString());
    }

    //初始化paystack订单（尼日）
    public void orderRepaySDK(String cardNumber, String expiryYear, String expiryMonth, String cvv) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("cardNumber", cardNumber.trim());
            jsonObject.put("expiryYear", expiryYear.trim());
            jsonObject.put("expiryMonth", expiryMonth.trim());
            jsonObject.put("cvv", cvv.trim());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request(UrlInfo_burnin.getInstance().getOgh(), getRequestJson(jsonObject).toString());
    }

    //获取paystack卡列表（尼日）
    public void bankList_niri() {
        request(UrlInfo_burnin.getInstance().getJtw(), getRequestJson().toString());
    }

    //线下还款-创建虚拟账号还款
    public void createVirtualAccount() {
        request(UrlInfo_burnin.getInstance().getBhr(), getRequestJson().toString());
    }

    /**
     * 保存页面显示/隐藏打点
     */
    public void saveUserBuriedPoint(String pageEvent) {
        new Thread(() -> {
            try {
                JSONObject jsonObject = getRequestJson();
                jsonObject.put("type", Constant_burnin.PRODUCT +"_"+pageEvent);

                final String gurl = Url_burnin.Url_Base + Url_burnin.PATH_GLOBAL + Url_burnin.PATH_USER_BURIED_POINT;
                Request request = new Request.Builder()
                        .url(gurl)
                        .post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonObject.toString()))
                        .build();

                Call call = mClient.newCall(request);
                call.execute();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * 保存firebase s2s需要信息
     */
    public void saveFirebaseS2SInfo() {
        new Thread(() -> {
            try {
                String gversion = BaseApplication_burnin.getApplication_burnin()
                        .getPackageManager()
                        .getPackageInfo(BaseApplication_burnin.getApplication_burnin().getPackageName(), PackageManager.GET_META_DATA)
                        .versionName;

                JSONObject jsonObject = getRequestJson();
                jsonObject.put("name", Constant_burnin.NAME);
                jsonObject.put("OSAndVersion", ("Android " + Build.VERSION.RELEASE));
                jsonObject.put("locale", Locale.getDefault().toString());
                jsonObject.put("device", Build.MODEL);
                jsonObject.put("appVersion", gversion);
                jsonObject.put("sdkVersion", gversion);
                jsonObject.put("build", "Build/" + Build.ID);
                jsonObject.put("lat", AnalyticsUtil_burnin.INSTANCE.getAdEnabled() + "");
//                jsonObject.put("firebaseAppId", FirebaseHelper.FIREBASE_APPID);
//                jsonObject.put("ga4AppInstanceId", FirebaseHelper.GA4_APP_INSTANCE_ID);

                final String gurl = Url_burnin.Url_Base + Url_burnin.PATH_FIREBASE_S2S;
                Request request = new Request.Builder()
                        .url(gurl)
                        .post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonObject.toString()))
                        .build();

                Call call = mClient.newCall(request);
                call.execute();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

}
